from bs4 import BeautifulSoup
import csv
import re


html_text = open('1.html').read()

soup = BeautifulSoup(html_text, "html.parser") 

name = soup.find_all("div", class_="title")
info = soup.find_all("div", class_="houseInfo")
tot_price = soup.find_all("div", class_="totalPrice")
unit_price = soup.find_all("div", class_="unitPrice")
location = soup.find_all("div", class_="positionInfo")

attr_name = ['户型','面积（平米）','朝向','装修','楼层']

items = []

for i in range(len(info)):
    d = {}

    d['标题'] = name[i].text.strip()

    l = info[i].text.split('|')
    for k in range(len(attr_name)):
        d[attr_name[k]] = l[k].strip()

    d['面积（平米）']    = float(re.findall("\d+", d['面积（平米）'])[0])

    d['总价（万）']      = float(re.findall("\d+", tot_price[i].text.strip())[0])
    d['单价（元/平米）'] = float(re.findall("\d+", unit_price[i].text.strip())[0])
    d['位置']           = location[i].text.strip()
    
    items.append(d)

f = open('1.csv', mode='w', encoding='utf-8-sig')

head = ['标题'] + attr_name + ['总价（万）', '单价（元/平米）', '位置']

writer = csv.DictWriter(f, fieldnames=head)

writer.writeheader()
writer.writerows(items)

f.close()

choice = {1:'标题', 2:'面积（平米）', 3:'单价（元/平米）', 4:'总价'}

c = 1

desc_order = False

x = """
1、按名称排序
2、按面积排序
3、按单价排序
4、按总价排序
S、升序
J、降序
Q、退出
"""

run = True

while run:
    print(x)
    s = input().strip()
    if len(s) > 1:
        print('Wrong Option!')
        continue
    if s.isalpha():
        if s == 'S': desc_order = False
        elif s == 'J': desc_order = True
        elif s == 'Q': 
            run = False
            break
        else:
            print('Wrong Option!')
            continue
    elif s.isdigit():
        if int(s) not in choice.keys():
            print('Wrong Option!')
            continue
        else:
            c = int(s)
    else:
        print('Wrong Option!')
        continue
    items.sort(key=lambda d:d[choice[c]], reverse=desc_order)
    for i in items: print(i)
